﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Yugi.Client.WebSerive;
using Yugi.Client.ViewModel;
using Yugi.Client;
using Yugi_Gui.Util_Control;
using Yugi_Gui.COntrol;
using System.Collections;

namespace Yugi_Gui
{
	/// <summary>
	/// Interaction logic for RoomLayout.xaml
	/// </summary>
	public partial class RoomLayout : UserControl , IInvoke
	{
        MainServerHandler mainserver;
        WebServiceCommunication cm= new WebServiceCommunication();
        RoomModel model;
		public RoomLayout()
		{
			this.InitializeComponent();
            this.Loaded += new RoutedEventHandler(RoomLayout_Loaded);
            this.create.OnClick += new Action<object>(create_OnClick);
            this.update.OnClick += new Action<object>(update_OnClick);
            this.deck.OnClick += new Action<object>(deck_OnClick);
            this.back.OnClick += new Action<object>(back_OnClick);
            this.autofind.OnClick += new Action<object>(autofind_OnClick);
            this.Sort += new Action<object, int[]>(RoomLayout_Sort);
		}

        void autofind_OnClick(object obj)
        {
            try
            {
                int TableID = this.list_table.GetTableRandom().ID;
                mainserver.SendMessageToServer(Common.MSG_GSM.L_JoinTable, TableID);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        void back_OnClick(object obj)
        {
            LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.Externa);
        }
       

        void RoomLayout_Loaded(object sender, RoutedEventArgs e)
        {
            mainserver = ((Window)(this.Parent)).DataContext as MainServerHandler;
            model = mainserver.Room_Model;
            model.Presenter = this;
            this.list_table.OnChoice += new Action<object>(list_table_OnChoice);
            list_user.ContexMenu += new Action<object, object>(list_user_ContexMenu);
            cbb_sort_table.Items.Add("Sort by ID");
            cbb_sort_table.Items.Add("Sort by CreaterName");
            if (model.tableinfo_s==null)
            {
                model.tableinfo_s = new List<TableInfo>();
                Action<Object> tmp = (o) =>
                {
                    this.list_table.Delete(0);
                    List<TableInfo> list = o as List<TableInfo>;
                    foreach (var item in list)
                    {
                        model.AddTableInfo(item);
                        this.list_table.AddTable(item);
                    }
                    this.status.Text = "Complete";
                };

                cm.SetAuth("yugioh", "admin123");
                cm.UpdateListTableAsync(this, tmp, mainserver.Current_Room_ID);
                UpdateUserOfRoom(null);
                this.status.Text = "Loading.........";
            }
            else
            {
                foreach (var item in model.tableinfo_s)
                {
                    this.list_table.AddTable(item);
                }
                foreach (var item in model.user_s)
                {
                    this.list_user.AddUser(item);
                }
            }
        }

        void list_user_ContexMenu(object obj1, object obj2)
        {
            PlayerInfo playerinfo = (PlayerInfo)obj1;
            MenuItem mi = (MenuItem)obj2;
            if (playerinfo == null || mi == null)
                return;
            if (mi.Name == "add_to_friend")
            {
                //mainserver.SendMessageToServer(Common.MSG_GSM.L_Add_Friend, (int)playerinfo.ID);
            }
            else if (mi.Name == "chat")
            {
                //do something
            }
        }
        void UpdateUserOfRoom(object obj)
        {
            model.user_s = new List<PlayerInfo>();
            Action<Object> tmp = (o) =>
            {
                list_user.listView.Items.Clear();
                List<PlayerInfo> list = o as List<PlayerInfo>;
                foreach (var item in list)
                {
                    model.AddUser(item);
                    this.list_user.AddUser(item);
                }
                this.status.Text = "Complete";
            };
            cm.UpdateListUserAsync(this, tmp, mainserver.Current_Room_ID);
            this.status.Text = "Loading.........";
        }
        void update_test()
        {
            cm.UpdateListTable(mainserver.Current_Room_ID);
        }
        void update_OnClick(object obj)
        {
            Action<Object> tmp = (o) =>
            {
                this.list_table.Delete(0);
                List<TableInfo> list = o as List<TableInfo>;
                foreach (var item in list)
                {
                    this.list_table.AddTable(item);
                }
                this.status.Text = "Complete";
            };
            cm.UpdateListTableAsync(this, tmp, mainserver.Current_Room_ID);
            this.status.Text = "Loading.........";
        }

        void create_OnClick(object obj)
        {
            mainserver.SendMessageToServer(Common.MSG_GSM.L_CreateTable, mainserver.Current_Room_ID);   
        }

        void list_table_OnChoice(object obj)
        {
            TableInfo tmp = obj as TableInfo;
            if (tmp == null)
                LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.PlayGame);
            else
            {
                mainserver.SendMessageToServer(Common.MSG_GSM.L_JoinTable, tmp.TableID);
                this.mainserver.Current_Table_ID = tmp.TableID;
            }
        }
        void deck_OnClick(object obj)
        {
            LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.Deck);
        }
        #region IInvoke Members

        public void Do(ClientMSG msg, params object[] obj)
        {
            switch(msg)
            {
                case ClientMSG.RecurrenceTable_OK:
                    TableInfo tableinfo = new TableInfo();
                    tableinfo.TableID = Convert.ToInt32(obj[0]);
                    tableinfo.NickName1 = (string)obj[1];
                    tableinfo.Payment = Convert.ToInt32(obj[2]);
                    tableinfo.CardID = Convert.ToInt32(obj[3]);
                    tableinfo.Comment = (string)obj[4];
                    model.AddTableInfo(tableinfo);
                    list_table.AddTable(tableinfo);
                    if (mainserver.External_Model.UserID == Convert.ToInt32(obj[5]))
                    {
                        this.mainserver.Current_Table_ID = -1;
                        LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.Room);
                    }
                    break;
                case ClientMSG.OutTable_OK:
                    model.RemoveTableInfo(Convert.ToInt32(obj[0]));
                    list_table.RemoveTable(Convert.ToInt32(obj[0]));
                    if (mainserver.External_Model.UserID == Convert.ToInt32(obj[1]))
                    {
                        this.mainserver.Current_Table_ID = -1;
                        LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.Room);
                    }
                    else if (mainserver.Current_Table_ID == Convert.ToInt32(obj[0]))
                    {
                        this.mainserver.Current_Table_ID = -1;
                        LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.Room);
                    }
                    break;
                case ClientMSG.CreateTable_OK:
                    TableInfo tableinfo2 = new TableInfo();
                    tableinfo2.TableID = Convert.ToInt32(obj[0]);
                    tableinfo2.NickName1 = (string)obj[1];
                    tableinfo2.Payment = Convert.ToInt32(obj[2]);
                    tableinfo2.CardID = Convert.ToInt32(obj[3]);
                    tableinfo2.Comment = (string)obj[4];
                    model.AddTableInfo(tableinfo2);
                    list_table.AddTable(tableinfo2);
                    if (mainserver.External_Model.UserID == Convert.ToInt32(obj[5]))
                    {
                        this.mainserver.Current_Table_ID = Convert.ToInt32(obj[0]);
                        Yugi.Client.Program.IP_SERVER = obj[6].ToString();
                        Yugi.Client.Program.PORT_SERVER = Int32.Parse(obj[7].ToString());
                        LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.PlayGame);
                    }
                    break;
                case ClientMSG.JoinTable_OK:
                    model.RemoveTableInfo(Convert.ToInt32(obj[0]));
                    list_table.RemoveTable(Convert.ToInt32(obj[0]));
                    if (mainserver.External_Model.UserID == Convert.ToInt32(obj[1]))
                    {
                        this.mainserver.Current_Table_ID = Convert.ToInt32(obj[0]);
                        Yugi.Client.Program.IP_SERVER = obj[2].ToString();
                        Yugi.Client.Program.PORT_SERVER = Int32.Parse(obj[3].ToString());
                        LayoutManager.LayoutManager.Insitance.ChangeToLayout(LayoutManager.LayoutType.PlayGame);
                    }
                    break;
                case ClientMSG.Update_JoinRoom_OK:
                    if (mainserver.External_Model.UserID != Convert.ToInt32(obj[0]))
                    {
                        PlayerInfo playerinfo = new PlayerInfo();
                        playerinfo.ID = Convert.ToInt32(obj[0]);
                        playerinfo.NickName = (string)obj[1];
                        playerinfo.IsOnline = 1;
                        model.AddUser(playerinfo);
                        list_user.AddUser(playerinfo);
                    }
                    break;
                case ClientMSG.Update_OutRoom_OK:
                    if (mainserver.External_Model.UserID != Convert.ToInt32(obj[0]))
                    {
                        model.RemoveUser(Convert.ToInt32(obj[0]));
                        list_user.RemoveUser(Convert.ToInt32(obj[0]));
                    }
                    break;
            }
        }

        public void Refresh()
        {
            //update_OnClick(null);
        }
        #endregion

        internal void GameLayout_Unloaded()
        {
            try
            {
                mainserver.SendMessageToServer(Common.MSG_GSM.L_OutRoom, mainserver.Current_Room_ID);

            }
            catch (Exception ex)
            {
            }
        }

        private void cbb_sort_table_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int[] op = new int[20];
            if (cbb_sort_table.SelectedIndex == 0)
                op[0] = Yugi_Gui.Sort_Search.Sort.Increase(Yugi_Gui.Sort_Search.Sort.VALUE_CP.TableID);
            if (cbb_sort_table.SelectedIndex == 1)
                op[0] = Yugi_Gui.Sort_Search.Sort.Reduction(Yugi_Gui.Sort_Search.Sort.VALUE_CP.NickName);
            if(Sort!=null)
                Sort("sort_table", op);
        }
        private void comboBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        void RoomLayout_Sort(object obj, int[] op)
        {
            if (obj.ToString() == "sort_table")
            {
                Sort_Search.Sort sort = new Sort_Search.Sort(this.list_table.layout.Children);
                List<UserControl> list = sort.Sortlist(op);
                for (int i = 0; i < list.Count; i++)
                {
                    int d = 10;
                    WpfApplication1.Table tmp = (WpfApplication1.Table)list[i];
                    tmp.Margin = new Thickness((i) * (d + 130), 0, 0, 0);
                }
            }
        }
        public event Action<object, int[]> Sort;
    }
}